//
//  RegisterViewController.m
//  JunZeWristband
//
//  Created by Kendama on 2017/8/16.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterView.h"
#import "WebViewController.h"
#import "PhoneTextFieldView.h"
#import "PasswordTextFieldView.h"
#import "VerifyTextFieldView.h"

#import "PublicRegisterApi.h"
#import "PublicGetRegisterCodeApi.h"

@interface RegisterViewController ()

@property(nonatomic,strong) RegisterView *containerView;

@end

@implementation RegisterViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    
}

- (void)refreshBaseControlValue
{
    
}

#pragma mark - 点击事件
- (void)getVerifyCode
{
    if (![self.containerView.phoneView.phoneTextField.text isMobileNumber]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码..."];
        return;
    }
    
    [self getVerifyCodeNumber];
}

// 获得验证码
- (void)getVerifyCodeNumber {
    [SVProgressHUD showInfoWithStatus:@"正在获取验证码..."];

    PublicGetRegisterCodeApi * codeApi = [[PublicGetRegisterCodeApi alloc] initWithDic:@{@"username":self.containerView.phoneView.phoneTextField.text}];
    [codeApi dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        NSDictionary * codeDic = [request responseJSONObject];
        [SVProgressHUD showInfoWithStatus:codeDic[@"errmsg"]];
        [self setVerifyBtnTimer];
        SAVE_OBJECT(codeDic[@"vcode"], @"vcode");
    } failure:nil];

}

- (void)didClickRegisterButton
{

    if (![self.containerView.phoneView.phoneTextField.text isMobileNumber]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码..."];
        return;
    }

    if (![self.containerView.passwordView.passwordTextField.text isRegexPassword]) {
        [SVProgressHUD showErrorWithStatus:@"请输入符合规定的密码"];
        return;
    }

    if (self.containerView.verifyView.verifyTextField.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"亲，还未输入验证码..."];
        return;
    }

    if (self.containerView.verifyView.verifyTextField.text.length < 6 || self.containerView.verifyView.verifyTextField.text.length > 6) {
        [SVProgressHUD showErrorWithStatus:@"亲，请输入6位验证码..."];
        return;
    }

    [self registerActionStart];
}



- (void)didClickProtocolButton
{
    WebViewController *vc = [[WebViewController alloc] init];
    vc.webViewType = UserAgreement;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)backBtnAction:(id)sender {
    
    NSArray * viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count > 1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count-1] == self) {
            [self.navigationController popViewControllerAnimated:YES];  //push方式
        }
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];   //present方式
    }
}

#pragma mark - 事件处理
// 设置定时器
- (void)setVerifyBtnTimer {
//    @weakify(self);
//    [self.containerView.verifyView.verifyButton setTitle:@"获取验证码" forState:0];
//    __block NSInteger code_out = 60;
//
//    RACSignal *timeSignal = [[[[RACSignal interval:1.0f onScheduler:[RACScheduler mainThreadScheduler]] take:code_out] startWith:@(1)] doNext:^(NSDate *date) {
//        @strongify(self);
//        NSLog(@"%@", date);
//        if (code_out == 0)
//        {
//            [self.containerView.verifyView.verifyButton setTitle:@"重新发送" forState:0];
////            [self.containerView.verifyView.verifyButton setTitle:@"60秒后获取" forState:UIControlStateDisabled];
//            self.containerView.verifyView.verifyButton.enabled = YES;
//        }
//        else
//        {
//            NSString * time = [NSString stringWithFormat:@"%ld %@",(long)code_out--,@"秒后获取"];
//            [self.containerView.verifyView.verifyButton setTitle:time forState:UIControlStateDisabled];
//            self.containerView.verifyView.verifyButton.enabled = NO;
//            
//        }
//    }];
//    
//    self.containerView.verifyView.verifyButton.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
//        code_out = 60;
//        return timeSignal;
//    }];
    __block int code_out = 60;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (code_out <= 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [_containerView.verifyView.verifyButton setTitle:@"获取验证码" forState:0];
                [_containerView.verifyView.verifyButton setTitle:@"60秒后获取" forState:UIControlStateDisabled];
                _containerView.verifyView.verifyButton.enabled = YES;
                code_out = 60;
            });
        } else {
            _containerView.verifyView.verifyButton.enabled = NO;
            NSString * time = [NSString stringWithFormat:@"%d %@",code_out,@"秒后获取"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_containerView.verifyView.verifyButton setTitle:time forState:UIControlStateDisabled];
            });
            code_out -- ;
        }
    });
    dispatch_resume(timer);
    
}

// 开始注册
- (void)registerActionStart
{
    NSString *phone = self.containerView.phoneView.phoneTextField.text;
    NSString *password = self.containerView.passwordView.passwordTextField.text;
    NSString *verify = self.containerView.verifyView.verifyTextField.text;
    [SVProgressHUD showInfoWithStatus:@"正在注册中..."];
    PublicRegisterApi * registerApi = [[PublicRegisterApi alloc] initWithDic:@{@"username":phone,@"password":password,@"vcode":verify}];
    [registerApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSDictionary * dict = [request responseJSONObject];
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            EMError *error = [[EMClient sharedClient] registerWithUsername:dict[@"data"][@"uid"] password:password];
//            if (!error)
//            {
                if (self.registerBlock)
                {
                    self.registerBlock(self.containerView.phoneView.phoneTextField.text, self.containerView.passwordView.passwordTextField.text);
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showSuccessWithStatus:dict[@"errmsg"]];
                });
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self backBtnAction:nil];
                });
//            }
//            else
//            {
//                [SVProgressHUD dismiss];
//                switch (error.code) {
//                    case EMErrorServerNotReachable:
//                        [SVProgressHUD showErrorWithStatus:@"连接服务器失败"];
//                        break;
//                    case EMErrorUserAlreadyExist:
//                        [SVProgressHUD showErrorWithStatus:@"用户已存在"];
//                        break;
//                    case EMErrorNetworkUnavailable:
//                        [SVProgressHUD showErrorWithStatus:@"没有网络"];
//                        break;
//                    case EMErrorServerTimeout:
//                        [SVProgressHUD showErrorWithStatus:@"连接超时"];
//                        break;
//                    case EMErrorServerServingForbidden:
//                        [SVProgressHUD showErrorWithStatus:@"服务被禁用"];
//                        break;
//                    default:
//                        [SVProgressHUD showErrorWithStatus:@"注册失败"];
//                        break;
//                }
//            }
//
//
//        });
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD showErrorWithStatus:[request responseJSONObject][@"errmsg"]];
    }];

}

#pragma mark - 代理


#pragma mark - 通知处理

#pragma mark - 初始化
- (RegisterView *)containerView
{
    if(!_containerView)
    {
        UIView *superView = self.view;
        _containerView = [[RegisterView alloc]init];
        [superView addSubview:_containerView];
        [_containerView.verifyView.verifyButton addTarget:self action:@selector(getVerifyCode) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.protocolButton addTarget:self action:@selector(didClickProtocolButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.registerButton addTarget:self action:@selector(didClickRegisterButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _containerView;
}

- (void)setNavigationStyle
{

    [self setNavigationTitle:@"注册" titleColor:[UIColor whiteColor]];
}

- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(superView);

    }];
}

@end
